package com.tanhua.admin.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.db.PageResult;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.gson.annotations.JsonAdapter;
import com.tanhua.dubbo.api.MovementApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.VideoApi;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.vo.MovementsVo;
import com.tanhua.model.vo.PageResultVo;
import com.tanhua.utils.Constants;
import org.apache.commons.collections.map.HashedMap;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Description: test
 * @Create by: JJ菜菜
 * @Date: 2021/12/8 23:54
 */
@Service
public class ManagerService {


    @DubboReference
    private UserInfoApi userInfoApi;

    @DubboReference
    private VideoApi videoApi;

    @DubboReference
    private MovementApi movementApi;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询所有用户列表
     * @param page
     * @param pagesize
     * @return
     */
    public PageResultVo findAllUsers(Integer page, Integer pagesize){

        //1、调用API分页查询数据列表   Ipage<UserInfo>
        IPage<UserInfo> iPage = userInfoApi.findAll(page,pagesize);
        //2、需要将Ipage转化为PageResult
        PageResultVo result = new PageResultVo(page, pagesize, (int) iPage.getTotal(), iPage.getRecords());
        //3、构造返回值
        return result;
    }


    /**
     * 根据用户id查询用户信息
     * @param usersId
     * @return
     */
    public UserInfo findUserInfoById(Long usersId) {

        UserInfo userInfo = userInfoApi.findById(usersId);
        if(redisTemplate.hasKey(Constants.FREEZE_USER+userInfo.getId())) {
            userInfo.setUserStatus("2");
        }
        return userInfo;
    }

    /**
     * 分页视频查询
     * @param page
     * @param pagesize
     * @param uid
     * @return
     */
    public PageResultVo findAllVideos(Integer page, Integer pagesize, Long uid) {


        PageResultVo pageResultVo = videoApi.findByUserId(page, pagesize, uid);
        return pageResultVo;
    }

    /**
     * 查看动态分页
     * @param page
     * @param pagesize
     * @param uid
     * @param state
     * @return
     */
    public PageResultVo findAllMovements(Integer page, Integer pagesize, Long uid, Integer state) {

        //1、调用API查询数据 ：Movment对象
        PageResultVo result = movementApi.findByUserId(uid,state,page,pagesize);
        //2、解析PageResult，获取Movment对象列表
        List<Movement> items = (List<Movement>) result.getItems();
        //3、一个Movment对象转化为一个Vo
        if(CollUtil.isEmpty(items)) {
            return new PageResultVo();
        }
        List<Long> userIds = CollUtil.getFieldValues(items, "userId", Long.class);
        Map<Long, UserInfo> map = userInfoApi.findByIds(null, userIds);
        List<MovementsVo> vos = new ArrayList<>();
        for (Movement movement : items) {
            UserInfo userInfo = map.get(movement.getUserId());
            if(userInfo != null) {
                MovementsVo vo = MovementsVo.init(userInfo, movement);
                vos.add(vo);
            }
        }
        //4、构造返回值
        result.setItems(vos);
        return result;

    }

    /**
     * 用户冻结
     * @param params
     * @return
     */
    public Map userFreeze(Map params) {

        // 冻结时间
        String ft = (String)params.get("freezingTime");
        int freezingTime = Integer.parseInt(ft);

        Integer id = (Integer) params.get("userId");

        int day = 0;
        if(freezingTime == 1){
            day = 3;
        }else if(freezingTime == 2){
            day = 7;
        }else if (freezingTime == 3) {
            // 永久冻结
            day = -1;
        }

        String value = JSON.toJSONString(params);

        // 将信息存到redis设置过期时间
        redisTemplate.opsForValue().set(Constants.FREEZE_USER + id, value, day, TimeUnit.DAYS);

        Map map = new HashedMap();
        map.put("message", "冻结成功");
        return map;

    }

    /**
     * 用户解冻
     * @param params
     */
    public Map userUnfreeze(Map params) {

        Integer userId = (Integer) params.get("userId");
        // 从redis中删除掉
        redisTemplate.delete(Constants.FREEZE_USER+userId);
        Map map = new HashMap();
        map.put("message","解冻成功");
        return map;

    }
}
